#include "shader_cg.h"
#include <iostream>

using namespace krryn::system_imp;

shader_cg::shader_cg(const std::string &a_Filename, CGcontext a_Context)
	: m_Filename(a_Filename), m_Context(a_Context)
{
}

void shader_cg::init(){
	m_Filename.append(".cg");

	std::clog << "Compiling shader '" << m_Filename << "'" << std::endl;

	// cgGetProfileString returns NULL if the profile is invalid.
	// there is no 'proper' way to test if a profile is valid.
	if(cgGetProfileString(m_VertexProfile) == NULL){
		std::clog << "Must initialize vertex profile before init()" << std::endl;
	}

	if(cgGetProfileString(m_PixelProfile) == NULL){
		std::clog << "Must initialize pixel profile before init()" << std::endl;
	}

	m_VertexShader = cgCreateProgramFromFile(
		m_Context, 
		CG_SOURCE,
		m_Filename.c_str(),
		m_VertexProfile,
		"v_main", NULL);
	check_error(m_Context);

	m_PixelShader = cgCreateProgramFromFile(
		m_Context,
		CG_SOURCE,
		m_Filename.c_str(),
		m_PixelProfile,
		"p_main", NULL);
	check_error(m_Context);
}

shader_cg::~shader_cg(){
	cgDestroyProgram(m_VertexShader);
	cgDestroyProgram(m_PixelShader);
}

void shader_cg::check_error(CGcontext cgContext) const{
	CGerror l_Error;
	const char* l_String = cgGetLastErrorString(&l_Error);
	if (l_Error == CG_COMPILER_ERROR){
		std::clog << cgGetLastListing(cgContext) << std::endl;
	}else if(l_Error != CG_NO_ERROR){
		std::clog << l_String << std::endl;
	}
}